# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def longestUnivaluePath(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        self.res = 0
        self.help(root)
        return self.res

    def help(self, node):
        if not node:
            return 0
        #         左节点的长度
        l = self.help(node.left)
        r = self.help(node.right)
        lc = rc = 0
        if node.left and node.left.val == node.val:
            lc = l + 1
        if node.right and node.right.val == node.val:
            rc = r + 1
        self.res = max(self.res, lc + rc)
        return max(lc, rc)





m1 = TreeNode(1)
m1.left = TreeNode(1)
m1.right = TreeNode(1)
# m1.left.left = TreeNode(4)
# m1.left.right = TreeNode(4)
# m1.right.left = TreeNode(5)
# m1.right.right = TreeNode(7)

s = Solution()

t = s.longestUnivaluePath(m1)
print(t)

